<template>
  <el-form ref="ruleFormRef" :model="form" v-loading="loading">
    <draggable
      :list="form.formArray"
      ghost-class="ghost"
      chosen-class="chosenClass"
      animation="300"
      @start="onStart"
      @end="onEnd"
      :disabled="!isEditChild"
    >
      <transition-group>
        <pub-edit-description
          v-for="(item, index) in form.formArray"
          style="margin-bottom: 30px"
          :key="index"
          :ndColumns="2"
        >
          <pub-edit-description-item :span="1" label="名称" required>
            <el-form-item
              :prop="'formArray.' + index + '.name'"
              :rules="$formRules.input"
            >
              <pub-input v-model="item.name" />
            </el-form-item>
          </pub-edit-description-item>
          <pub-edit-description-item :span="1" label="编码" required>
            <el-form-item
              :prop="'formArray.' + index + '.code'"
              :rules="$formRules.input"
            >
              <pub-input v-model="item.code" />
            </el-form-item>
          </pub-edit-description-item>
          <pub-edit-description-item :span="1" label="状态" required>
            <el-form-item
              :prop="'formArray.' + index + '.status'"
              :rules="$formRules.select"
            >
              <pub-select-dict
                style="width: 100%"
                v-model="item.status"
                dict-code="ZDZT"
                placeholder="请选择"
              />
            </el-form-item>
          </pub-edit-description-item>
          <pub-edit-description-item
            :span="1"
            label="类别"
            required
            v-if="!isEditChild"
          >
            <el-form-item
              :prop="'formArray.' + index + '.type'"
              :rules="$formRules.select"
            >
              <pub-select-dict
                style="width: 100%"
                v-model="item.type"
                dict-code="ZDLX"
                placeholder="请选择"
              />
            </el-form-item>
          </pub-edit-description-item>
          <pub-edit-description-item :span="1" v-else></pub-edit-description-item>
          <div
            style="
              border-top: 1px solid rgb(235, 238, 245);
              width: 200%;
              padding: 10px 0;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <el-icon
              v-if="
                isEditChild || (currentPid === '' && form.formArray.length > 1)
              "
              style="vertical-align: middle; margin-left: 15px; cursor: pointer"
              :size="20"
            >
              <Delete @click="delDict(index)" />
            </el-icon>
            <el-icon
              v-if="
                (isEditChild || currentPid === '') &&
                index == form.formArray.length - 1
              "
              style="vertical-align: middle; margin-left: 15px; cursor: pointer"
              :size="20"
            >
              <CirclePlus @click="addDict" />
            </el-icon>
          </div>
          <!-- </pub-edit-description-item> -->
        </pub-edit-description>
      </transition-group>
    </draggable>
    <div class="options" v-if="(isEditChild || currentPid === '') && form.formArray.length === 0">
      <el-icon
        style="vertical-align: middle; margin-left: 15px; cursor: pointer"
        :size="20"
      >
        <CirclePlus @click="addDict" />
      </el-icon>
    </div>
    <div class="dialog-footer-btn">
      <el-button @click="cancel">取消</el-button>
      <el-button v-prevent-repeat-click type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
    </div>
  </el-form>
</template>

<script setup>
import { VueDraggableNext as Draggable } from 'vue-draggable-next'
import { ElMessage } from 'element-plus'
import {
  addPidDict,
  editPidDict,
  getChildrenDictByPid,
  getDictInfo,
  updateChildrenDict
} from '@/api/dict.js'
const emit = defineEmits(['cancel'])
const loading = ref(false)
const props = defineProps({
  isEditChild: {
    type: Boolean,
    default: false
  },
  currentPid: {
    type: String,
    default: ''
  },
  isSystem: {
    type: Number,
    default: 1
  }
})
const form = reactive({
  formArray: [
    {
      name: '',
      code: '',
      status: '1',
      type: ''
    }
  ]
})

const initDict = async () => {
  loading.value = true
  try {
    if (props.isEditChild) {
      // 获取子级
      const res = await getChildrenDictByPid(props.currentPid)
      if (res.data && res.data.length > 0) {
        form.formArray = res.data
      } else {
        form.formArray = [
          {
            name: '',
            code: '',
            status: '1',
            pid: props.currentPid
          }
        ]
      }
      loading.value = false
    } else {
      // 获取父级
      if (props.currentPid) {
        const res = await getDictInfo(props.currentPid)
        if (res.data) {
          form.formArray = [res.data]
        }
      } else {
        form.formArray = [
          {
            name: '',
            code: '',
            status: '1',
            type: '',
            isSystem: props.isSystem
          }
        ]
      }
      loading.value = false
    }
  } catch (error) {
    loading.value = false
  }
}
const ruleFormRef = ref()

const addDict = () => {
  if (props.isEditChild) {
    form.formArray.push({
      name: '',
      code: '',
      status: '1',
      pid: props.currentPid
    })
  } else {
    form.formArray.push({
      name: '',
      code: '',
      status: '1',
      type: '',
      isSystem: props.isSystem
    })
  }
}
const delDict = index => {
  form.formArray.splice(index, 1)
}
const cancel = () => {
  emit('cancel', false)
}

//拖拽开始的事件
const onStart = () => {
  console.log('开始拖拽')
}

//拖拽结束的事件
const onEnd = () => {}

const submitForm = formEl => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      loading.value = true
      if (props.isEditChild) {
        // 添加子字典
        const res = await updateChildrenDict(form.formArray, props.currentPid)
        if (res.succeed) {
          ElMessage({
            type: 'success',
            message: res.msg
          })
        }
      } else {
        let res = null
        if (props.currentPid) {
          // 编辑父字典
          res = await editPidDict(form.formArray[0])
        } else {
          // 新增父字典
          res = await addPidDict(form.formArray)
        }
        if (res.succeed) {
          ElMessage({
            type: 'success',
            message: res.msg
          })
        }
      }
      emit('cancel', false)
      loading.value = false
    } else {
      console.log('error submit!')
      return false
    }
  })
}

onMounted(() => {
  initDict()
})
</script>

<style scoped lang="scss">
.options {
  height: 20px;
  line-height: 20px;
  text-align: center;
  :deep(.el-icon) {
    margin-left: 0 !important;
  }
}
</style>
